package com.liry.security.config;

import com.alibaba.fastjson.JSONArray;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * @author ALI
 * @since 2023/6/17
 */
public class PermissionFilter extends OncePerRequestFilter {

    private final CacheManager cacheManager;

    public PermissionFilter(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain)
    throws ServletException, IOException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || authentication.getPrincipal() == null) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        if (authentication.getPrincipal() instanceof String) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        // 获取认证信息
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        if (authorities.isEmpty()) {
            throw new AccessDeniedException("无权限！");
        }
        // 获取权限信息
        Set<String> permissions = new HashSet<>();
        for (GrantedAuthority authority : authorities) {
            Object o = cacheManager.get(authority.getAuthority());
            if (o != null) {
                List<String> collect = JSONArray.parseArray(o.toString()).stream().map(Object::toString).collect(Collectors.toList());
                permissions.addAll(collect);
            }
        }
        if (permissions.isEmpty()) {
            throw new AccessDeniedException("无权限！");
        }
        // 判断是否有权限访问
        String api = servletRequest.getRequestURI();
        if (!permissions.contains(api)) {
            throw new AccessDeniedException("无权限！");
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
